﻿using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;
using System.Data;
using System.Text;
using System.Linq;
using System.Data.SqlClient;
using System.Configuration;
using Square.Activity;
using System.Reflection;

namespace Square.CONTROLTEMPLATES.Square
{
    public partial class People_List : UserControl
    {
        #region ## DataTableColumns
        private string _idx = "IDX";
        private string _id = "ID";
        private string _displayName = "DISPLAYNAME";
        private string _recordID = "RECORDID";
        private string _groupTitle = "GROUPTITLE";
        #endregion

        #region ## Properties
        public string _siteUrl { get { return SPContext.Current.Site.Url; } }
        public string _webUrl { get { return SPContext.Current.Web.Url; } }
        private string _listUrl { get { return "/my/Lists/Sq_Colleagues"; } }
        private string _listName { get { return "Sq_Colleagues"; } }

        public string _accountName
        {
            get
            {
                if (Request.QueryString["accountname"] != null)
                    return Request.QueryString["accountname"];
                else
                    return this.Page.User.Identity.Name;
                    //return hd_accountName.Value;
            }
        }
        
        public UserProfile _pageUserProfile;
        public int _pageNum = 1;
        public int _cntNum = 0;
        public int _addCount = 25;
        public bool chkAccunt = false;
        
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {   
            if (!IsPostBack)
            {   
                hd_accountName.Value = _accountName;
                hd_siteUrl.Value = _siteUrl;
                Colleagues_List();
                //group_Search_list();
                //Page.ClientScript.RegisterStartupScript(this.GetType(), null, "fn_jButton();", true);
                SquareActivityHelper sHelper;
                sHelper = new SquareActivityHelper();
                sHelper.SetupActivities(this.Page);

                SquareActivities Atype = new SquareActivities();
                Atype = SquareActivities.PeopleAll;
                ActViewer.SquareActivityType = Atype;
            }
            if (_accountName == this.Page.User.Identity.Name)
                chkAccunt = true;
            else
                chkAccunt = false;
            
        }

        #region ## 동료 전체 목록 호출
        public void Colleagues_List()
        {
            DataTable dt_colleagues = new DataTable();

            string siteUrl = string.Empty;
            string accountName = string.Empty;

            siteUrl = _siteUrl;
            if (_siteUrl == null) siteUrl = hd_siteUrl.Value;
            accountName = _accountName;
            if (_accountName == null) accountName = hd_accountName.Value;

            using (SPSite site = new SPSite(siteUrl))
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    SPServiceContext context = SPServiceContext.GetContext(site);
                    //ServerContext context = ServerContext.GetContext(site);
                    UserProfileManager upm = new UserProfileManager(context);


                    if (upm.UserExists(accountName))
                    {
                        _pageUserProfile = upm.GetUserProfile(accountName);

                        if (_pageUserProfile != null)
                        {
                            UserProfile[] impersUser = _pageUserProfile.Colleagues.GetCommonColleagues();

                            // userprofile 정보
                            dt_colleagues.Columns.Add(_idx);
                            dt_colleagues.Columns.Add(_id);
                            dt_colleagues.Columns.Add(_displayName);
                            dt_colleagues.Columns.Add(_recordID);
                            dt_colleagues.Columns.Add(_groupTitle);

                            // List Sq_GroupMembers 정보
                            
                            for (int i = 0; i < impersUser.Length; i++)
                            {
                                if (!string.IsNullOrEmpty(Request.QueryString["grouptitle"]))
                                {
                                    string _groupTitleVal = HttpUtility.UrlDecode(Request.QueryString["grouptitle"]);
                                    if (ColleagueGroupName(impersUser[i].RecordId.ToString()).Contains(_groupTitleVal) == true)
                                    {
                                        DataRow dr = dt_colleagues.NewRow();
                                        dr[_idx] = i.ToString();
                                        dr[_id] = colleagueID(impersUser[i].RecordId.ToString(), site);
                                        dr[_displayName] = impersUser[i].DisplayName;
                                        dr[_recordID] = impersUser[i].RecordId;
                                        dr[_groupTitle] = ColleagueGroupName(impersUser[i].RecordId.ToString());
                                        dt_colleagues.Rows.Add(dr);
                                    }
                                }
                                else
                                {
                                    DataRow dr = dt_colleagues.NewRow();
                                    dr[_idx] = i.ToString();
                                    dr[_id] = colleagueID(impersUser[i].RecordId.ToString(), site);
                                    dr[_displayName] = impersUser[i].DisplayName;
                                    dr[_recordID] = impersUser[i].RecordId;
                                    dr[_groupTitle] = ColleagueGroupName(impersUser[i].RecordId.ToString());
                                    dt_colleagues.Rows.Add(dr);
                                }
                            }
                        }
                    }
                });
            }
            Colleague_Info(dt_colleagues);
        }
        #endregion

        #region ## 동료의 상세 정보 호출
        public void Colleague_Info(DataTable colleaguesDT)
        {
            DataTable dt_list = colleaguesDT;
            StringBuilder sb = new StringBuilder();
            string dt_id = string.Empty;

            if (dt_list.Rows.Count > 0)
            {
                using (SPSite _site = new SPSite(_siteUrl))
                {
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        SPServiceContext context = SPServiceContext.GetContext(_site);
                        UserProfileManager upm = new UserProfileManager(context);

                        UserProfile _cProfile;
                        int maxCount = 0;

                        // 그룹 타입 / 조직 // 페이징 // 권한 
                        sb.Append("<table class=\"width100\">");
                        //sb.Append("     <tr>"); // 첫줄
                        //sb.Append("         <td colspan=\"5\">&nbsp;");
                        //sb.Append("             <a href=\"javascript:Toggle();\" title=\"\"><img name=\"qcbToggleUsers\" border=0 id=\"qcbToggleUsers\"  alt=\"\"  src=\"/_layouts/images/unchecka.gif\"/></a>");
                        //sb.Append("         </td>");
                        //sb.Append("     </tr>");
                        sb.Append("     <tr>");

                        // 5명 한줄 돌리기
                        if (string.IsNullOrEmpty(Request.QueryString["maxC"]))
                        {
                            hd_MaxItem.Value = _addCount.ToString();
                        }
                        else
                        {
                            hd_MaxItem.Value = HttpUtility.UrlDecode(Request.QueryString["maxC"]);
                            hd_MaxItem.Value = (Convert.ToInt32(hd_MaxItem.Value) + _addCount).ToString();
                        }

                        if (Convert.ToInt32(hd_MaxItem.Value) < dt_list.Rows.Count)
                            maxCount = Convert.ToInt32(hd_MaxItem.Value);
                        else
                            maxCount = dt_list.Rows.Count;

                        for (_cntNum = 0; _cntNum < maxCount; _cntNum++)
                        {
                            dt_id = dt_list.Rows[_cntNum][_id].ToString();
                            _cProfile = upm.GetUserProfile(int.Parse(dt_list.Rows[_cntNum][_recordID].ToString()));

                            colleagues_Group(_cProfile, sb, dt_id, dt_list.Rows[_cntNum][_recordID].ToString());

                            // Count % 5이면 줄바꿈 추가 
                            if ((_cntNum + 1) % 5 == 0)
                            {
                                sb.Append("     </tr>");
                                sb.Append("     <tr>");
                            }
                        }

                        // 빈칸 메우기
                        if (dt_list.Rows.Count <= maxCount && dt_list.Rows.Count % 5 != 0)
                        {
                            for (int i = 0; i < 5 - (dt_list.Rows.Count % 5); i++)
                            {
                                sb.Append("<td class=\"lit_people_img_TD\">&nbsp</td>");
                            }
                        }

                        sb.Append("     </tr>");

                        // 일회 출력 최대치 오버 시 더보기 버튼
                        if (maxCount < dt_list.Rows.Count)
                        {
                            sb.Append("     <tr>");
                            sb.Append("         <td colspan=\"5\" class=\"list_more_TD\" >");
                            sb.Append("             <div class=\"list_more_Div\" onclick=\"fn_ListMore();\">More</div>");
                            sb.Append("         </td>");
                            sb.Append("     </tr>");
                        }
                        sb.Append("</table>");
                    });
                }
                
                lbl_list.Text = sb.ToString();
            }
            else
            {
                lbl_list.Text = "&nbsp;";
            }
        }
        #endregion

        #region ## 목록 호출
        public void colleagues_Group(UserProfile userInfo, StringBuilder sb, string dt_id, string dt_recordId)
        {
            string[] strName = userInfo["PreferredName"].Value.ToString().Split('\\');

            sb.Append("         <td class=\"lit_people_img_TD\">"); // 동료 한명의 정보
            sb.Append("             <table>");
            sb.Append("                 <tr>");
            sb.Append("                     <td class=\"list_chkbox_TD\" >"); // 체크 박스
            sb.Append("                         <input class=\"list_chkbox\" type=\"checkbox\" name=\"qcbCheckedUsers\" value=\"" + dt_id + "\" title=\"\" onclick=\"ClearToggle();\" id=\"qcbCheckedUsers\"/>");
            sb.Append("                     </td>");
            sb.Append("                     <td>"); // 사진
            sb.Append("                         <a class=\"tooltip\" href=\"" + userInfo.PersonalUrl + "\" target=\"_blank\" rel=\"" + (userInfo["SPS-StatusNotes"].Value != null ? userInfo["SPS-StatusNotes"].Value : "What's happening?") + "\">");
            if (userInfo["PictureURL"].Value != null)
                sb.Append("                         <img src=\"" + userInfo["PictureURL"].Value + "\" class=\"list_people_img\" />");
            else
                sb.Append("                         <img src=\"" + userInfo.PersonalUrl.Scheme + "://" + userInfo.PersonalUrl.Host + "/_layouts/images/O14_person_placeHolder_32.png\" class=\"list_people_img\" />");
            sb.Append("                         </a>");
            sb.Append("                     </td>");
            sb.Append("                 </tr>");
            sb.Append("                 <tr>");
            sb.Append("                     <td>&nbsp</td>");
            sb.Append("                     <td>" + strName[1] + "</td>"); // 이름
            sb.Append("                 </tr>");
            //sb.Append("                 <tr>");
            //sb.Append("                     <td>&nbsp</td>");
            //sb.Append("                     <td>" + ColleaguesGroupList(userInfo.RecordId.ToString()) + "</td>"); // 그룹 
            //sb.Append("                 </tr>");            
            sb.Append("                 <tr>");
            sb.Append("                     <td>&nbsp</td>");
            sb.Append("                     <td>" + userInfo["Department"].Value + " " + userInfo["SPS-JobTitle"].Value + "</td>"); // 부서 / 직함
            sb.Append("                 </tr>");
            sb.Append("                 <tr>");
            sb.Append("                     <td>&nbsp</td>");
            sb.Append("                     <td>" + userInfo["WorkPhone"].Value + "</td>"); // 회사 전화
            sb.Append("                 </tr>");
            sb.Append("             </table>");
            sb.Append("         </td>");
        }
        #endregion

        #region ## 사이드 메뉴 그룹 목록
        protected void group_Search_list()
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate() 
                {
                    using (SPSite _site = new SPSite(_siteUrl))
                    {
                        using (SPWeb _web = _site.OpenWeb())
                        {
                            //SPList _list = _web.GetList(_listUrl);
                            SPList _list = _web.Lists[_listName];
                            DataTable dt = new DataTable();
                            dt.Columns.Add("GroupTitle");

                            StringBuilder sb = new StringBuilder();
                            sb.Append("<OrderBy>");
                            sb.Append("<FieldRef Name=\"Created\" Ascending=\"False\" />");
                            sb.Append("</OrderBy>");
                            sb.Append("<Where>");
                            sb.Append(" <Eq>");
                            sb.Append("     <FieldRef Name=\"RecordId\" />");
                            sb.AppendFormat("     <Value Type=\"Text\">{0}</Value>", _pageUserProfile.RecordId);
                            sb.Append(" </Eq>");
                            sb.Append("</Where>");

                            SPQuery sq = new SPQuery();
                            sq.ViewFields = "<FieldRef Name=\"GroupTitle\" />";
                            sq.Query = sb.ToString();

                            SPListItemCollection _items = _list.GetItems(sq);

                            if (_items != null && _items.Count > 0)
                            {
                                foreach (SPListItem _item in _items)
                                {
                                    bool chkVal = true;
                                    DataRow dr = dt.NewRow();
                                    
                                    for (int i = 0; i < dt.Rows.Count; i++)
                                    {
                                        if (dt.Rows[i]["GroupTitle"].ToString() == _item["GroupTitle"].ToString())
                                        {
                                            chkVal = false;
                                            break;
                                        }
                                    }
                                    
                                    if (chkVal)
                                    {   
                                        dr["GroupTitle"] = _item["GroupTitle"];
                                        dt.Rows.Add(dr);
                                    }
                                }
                            }
                            //rp_GroupList.DataSource = dt;
                            //rp_GroupList.DataBind();
                        }
                    }
                });
            }
            catch (Exception ex)
            { throw new Exception(ex.ToString()); }
        }
        #endregion

        #region ## 동료의 등록된 그룹 찾기
        protected string ColleaguesGroupList(string recordID)
        {
            StringBuilder sb = new StringBuilder();
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate() 
                {
                    using (SPSite _site = new SPSite(_siteUrl))
                    {
                        using (SPWeb _web = _site.OpenWeb())
                        {
                            //SPList _list = _web.GetList(_listUrl);
                            SPList _list = _web.Lists[_listName];

                            var _items = from SPListItem item in _list.Items
                                         where (item["RecordId"] != null ? item["RecordId"].ToString() == _pageUserProfile.RecordId.ToString() : false)
                                                && (item["ColleagueRecordId"] != null ? item["ColleagueRecordId"].ToString() == recordID : false)
                                         select item;
                            if (_items != null && _items.Count() > 0)
                            {
                                foreach (SPListItem _item in _items)
                                {
                                    string gpName = string.Empty;
                                    if (_item["GroupTitle"] != null)
                                        gpName = _item["GroupTitle"].ToString();
                                    else
                                        gpName = "일반";

                                    if (_item["IsEnable"] == null || _item["IsEnable"].ToString() == "N")
                                    {   
                                        sb.Append(gpName + " 요청중");
                                        continue;
                                    }

                                    sb.Append(" " + gpName);
                                }
                            }
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                sb.Append(ex.ToString());
            }

            return sb.ToString();
        }
        #endregion

        #region ## 동료 ColleagueID 찾기
        public string colleagueID(string recordId, SPSite site)
        {
            string retRecordId = string.Empty;

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate() 
                {
                    using (SPWeb _web = site.OpenWeb())
                    {   
                        //SPList _list = _web.GetList(_listUrl);
                        SPList _list = _web.Lists[_listName];

                        StringBuilder sb = new StringBuilder();
                        sb.Append("<OrderBy>");
                        sb.Append("<FieldRef Name=\"Created\" Ascending=\"False\" />");
                        sb.Append("</OrderBy>");
                        sb.Append("<Where>");
                        sb.Append("     <And>");
                        sb.Append("         <Eq>");
                        sb.Append("             <FieldRef Name=\"RecordId\" />");
                        sb.AppendFormat("       <Value Type=\"Text\">{0}</Value>", _pageUserProfile.RecordId);
                        sb.Append("         </Eq>");
                        sb.Append("         <Eq>");
                        sb.Append("             <FieldRef Name=\"ColleagueRecordId\" />");
                        sb.AppendFormat("       <Value Type=\"Text\">{0}</Value>", recordId);
                        sb.Append("         </Eq>");
                        sb.Append("     </And>");
                        sb.Append("</Where>");

                        SPQuery sq = new SPQuery();
                        sq.ViewFields = "<FieldRef Name=\"Title\" /><FieldRef Name=\"RecordId\" /><FieldRef Name=\"Created\" />";
                        sq.Query = sb.ToString();
                        SPListItemCollection _items = _list.GetItems(sq);

                        if (_items.Count > 0)
                        {
                            if (_items[0]["Title"] != null && !string.IsNullOrEmpty(_items[0]["Title"].ToString()))
                                retRecordId = _items[0]["Title"].ToString();
                        }
                    }
                });
            }
            catch (Exception ex) { throw new Exception(ex.ToString()); }

            return retRecordId;
        }
        #endregion

        #region ## 동료 그룹 네임 찾기
        public string ColleagueGroupName(string recordID)
        {
            StringBuilder gName = new StringBuilder();

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite _site = new SPSite(_siteUrl))
                    {
                        using (SPWeb _web = _site.OpenWeb())
                        {
                            //SPList _list = _web.GetList(_listUrl);
                            SPList _list = _web.Lists[_listName];

                            var _items = from SPListItem item in _list.Items
                                         where (item["RecordId"] != null ? item["RecordId"].ToString() == _pageUserProfile.RecordId.ToString() : false)
                                                && (item["ColleagueRecordId"] != null ? item["ColleagueRecordId"].ToString() == recordID : false)
                                         select item;
                            if (_items != null && _items.Count() > 0)
                            {
                                foreach (SPListItem _item in _items)
                                {
                                    string gpName = string.Empty;
                                    if (_item["GroupTitle"] != null)
                                        gpName = _item["GroupTitle"].ToString();
                                    else
                                        gpName = "일반";

                                    gName.Append(gpName);
                                }
                            }
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }

            return gName.ToString();
        }
        #endregion

        #region ## DB Item ID 
        public DataSet GetColleagueID(UserProfile userProfile, UserProfile colleagueProfile)
        {
            DataSet ColleagueID = new DataSet();
            SqlDataAdapter adapter;
            StringBuilder ColleagueIDquery = new StringBuilder();

            SqlConnection profileConn = new SqlConnection();
            SqlConnection socialConn = new SqlConnection();
            string partitionid = string.Empty;
            string pConn = string.Empty;
            string sConn = string.Empty;

            if (System.Configuration.ConfigurationManager.ConnectionStrings["ProfileConn"] != null)
            {
                pConn = System.Configuration.ConfigurationManager.ConnectionStrings["ProfileConn"].ToString();
            }
            if (System.Configuration.ConfigurationManager.ConnectionStrings["SocialConn"] != null)
            {
                sConn = System.Configuration.ConfigurationManager.ConnectionStrings["SocialConn"].ToString();
            }

            try
            {
                profileConn.ConnectionString = pConn;
                socialConn.ConnectionString = sConn;
                profileConn.Open();
                socialConn.Open();
            }
            catch (Exception ex)
            {
                if (profileConn != null) profileConn.Dispose();
                if (socialConn != null) socialConn.Dispose();
                throw new Exception(ex.Message);
            }
            //ColleagueID를 가지고 온다
            using (SqlCommand command = new SqlCommand())//new SqlCommand("dbo.proc_SocialComments_GetForUser"))
            {
                partitionid = userProfile.Suggestions.GetType().GetProperty("PartitionID", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(userProfile.Suggestions, null).ToString();

                ColleagueIDquery.AppendLine("SELECT Id");
                ColleagueIDquery.AppendLine(" FROM UserColleagues (NOLOCK)");
                ColleagueIDquery.AppendFormat(" WHERE RecordId = '{0}'", userProfile.RecordId);
                ColleagueIDquery.AppendFormat(" and ColleagueRecordId = '{0}'", colleagueProfile.RecordId);
                //query.AppendLine(" and sc.LastModifiedTime >= @fromDate and sc.LastModifiedTime < @toDate");

                command.CommandText = ColleagueIDquery.ToString();
                command.Connection = profileConn;
                adapter = new SqlDataAdapter();
                adapter.SelectCommand = command;
                adapter.Fill(ColleagueID);

            }
            profileConn.Close();
            if (profileConn != null) profileConn.Dispose();
            socialConn.Close();
            if (socialConn != null) socialConn.Dispose();

            return ColleagueID;
        }
        #endregion

        public void lbtn_RequestCancel_Click(object sender, EventArgs e)
        {
            string rId = hd_RequestID.Value;

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite _site = new SPSite(_siteUrl))
                    {
                        using (SPWeb _web = _site.OpenWeb())
                        {
                            SPList _list = _web.GetList(_listUrl);
                            //SPList _list = _web.Lists[_listName];

                            SPServiceContext context = SPServiceContext.GetContext(_site);
                            //ServerContext context = ServerContext.GetContext(_site);
                            UserProfileManager upm = new UserProfileManager(context);

                            SPListItem _item = _list.GetItemById(Convert.ToInt32(rId));
                            _pageUserProfile = upm.GetUserProfile(_accountName);
                            UserProfile _colleaguesProfile = upm.GetUserProfile(long.Parse(_item["ColleagueRecordId"].ToString()));
                            DeleteColleague(_siteUrl, _accountName, _colleaguesProfile.DisplayName);

                            _web.AllowUnsafeUpdates = true;
                            _item.Delete();
                            _list.Update();
                            _web.AllowUnsafeUpdates = false;
                        }
                    }
                });
            }
            catch (Exception ex) { throw new Exception(ex.ToString()); }
        }

        /// <summary>
        /// Deletes a colleague relationship.
        /// </summary>
        /// <param name="requestUrl">URL of the SharePoint site to connect to.</param>
        /// <param name="loginName">Login name of a user having access to 
        /// the SharePoint site (for example, DOMAIN\User).</param>
        /// <param name="colleagueLoginName">Login name of the user to add 
        /// to loginName's colleagues (for example, DOMAIN\User).</param>
        public static void DeleteColleague(string requestUrl, string loginName, string colleagueLoginName)
        {
            using (SPSite siteCollection = new SPSite(requestUrl))
            {
                using (SPWeb webSite = siteCollection.OpenWeb())
                {
                    // Retrieve the ServerContext of the site collection.SPServiceContext
                    SPServiceContext serverContext = SPServiceContext.GetContext(siteCollection);
                    //ServerContext serverContext = ServerContext.GetContext(siteCollection);

                    // Connect to the UserProfileManager of the SharePoint Web application.
                    UserProfileManager userProfileManager = new UserProfileManager(serverContext);

                    // Check whether the user profile and the colleague user profile exist, and that they are not
                    // the same user.
                    if (userProfileManager.UserExists(loginName) &&
                        userProfileManager.UserExists(colleagueLoginName) &&
                        string.Compare(loginName, colleagueLoginName, true) != 0)
                    {
                        // Retrieve user profiles.
                        UserProfile userProfile = userProfileManager.GetUserProfile(loginName);
                        UserProfile userProfileColleague = userProfileManager.GetUserProfile(colleagueLoginName);

                        // Check whether colleagueLoginName is already a colleague.
                        if (userProfile.Colleagues.IsColleague(userProfileColleague.ID) == true)
                        {
                            userProfile.Colleagues[userProfileColleague].Delete();

                            // Save the modification made to the user profile.
                            userProfile.Commit();
                        }
                    }
                }
            }
        }
    }
}
